package service

import (
	"encoding/json"
	"errors"
	"github.com/go-admin-team/go-admin-core/sdk/service"
	"gorm.io/gorm"
	"tuowei.com/app/api/models"
	"tuowei.com/app/api/service/dto"
)

type ApiExerciseRecord struct {
	service.Service
}

func (e *ApiExerciseRecord) Insert(c *dto.SysExerciseRecordInsertReq, studentId int) error {
	var data models.SysExerciseRecord
	var model models.SysQuestionBankInsert
	err := e.Orm.Model(model).First(&model, c.ExId).Error
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		return errors.New("练习题不存在")
	}
	var practiceModel models.SysPracticeRecord
	err = e.Orm.Model(practiceModel).Where("student_id = ?", studentId).
		Where("ex_type = ?", c.ExerciseType).
		Where("obj_id = ?", c.LinkId).Order("id desc").First(&practiceModel).Error
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		return errors.New("练习记录不存在")
	}

	// 为什么有人不喜欢写注释都不知道是干什么的
	// 做过了,就不在插入了
	var exist bool
	err = e.Orm.Model(data).
		Where("ex_type = ?", c.ExerciseType).
		Where("link_id = ?", c.LinkId).
		Where("student_id = ?", studentId).
		Where("ex_id = ?", c.ExId).First(&data).Error
	if err == nil {
		//找到了,直接更新状态
		exist = true
	}

	//c.Generate(&data)
	data.ExId = c.ExId
	data.PracticeId = practiceModel.Id
	data.SubjectType = model.SubjectType
	data.ExerciseType = c.ExerciseType
	data.ChapterId = c.ChapterId
	data.SelectedAnswer = c.SelectedAnswer
	data.StudentId = studentId
	data.LinkId = c.LinkId
	if c.SelectedAnswer == model.CorrectAnswer {
		data.Status = 1
	} else {
		// 去除之前的异步
		e.handler(c, studentId)
		data.Status = 0
	}
	if !exist {
		data.Nums = 1
		return e.Orm.Create(&data).Error
	} else {
		// 此处由于status可能会被更改为0，gorm不处理0值。所以需要重新改成map形式
		m := make(map[string]interface{})
		data.Nums++
		bts, _ := json.Marshal(data)
		err = json.Unmarshal(bts, &m)
		err = e.Orm.Table(data.TableName()).Where("id = ?", data.Id).Updates(m).Error
		return err
	}

}

func (e *ApiExerciseRecord) handler(c *dto.SysExerciseRecordInsertReq, studentId int) {
	var data models.SysErrorRecord
	err := e.Orm.Model(data).
		Where("student_id = ?", studentId).
		Where("link_id = ?", c.LinkId).
		Where("link_type = ?", c.ExerciseType).
		Where("subject_type = ?", c.SubjectType).
		Where("ex_id = ?", c.ExId).First(&data).Error
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		data.LinkType = c.ExerciseType
		data.LinkId = c.LinkId
		data.ExId = c.ExId
		data.StudentId = studentId
		data.SubjectType = c.SubjectType
		data.ErrorFrequency = 1
		e.Orm.Model(data).Create(&data)
	} else {
		e.Orm.Model(data).Where("link_id = ?", c.LinkId).
			Where("student_id = ?", studentId).
			Where("ex_id = ?", c.ExId).
			Where("link_type = ?", c.ExerciseType).
			Where("subject_type = ?", c.SubjectType).
			Update("error_frequency", gorm.Expr("error_frequency + ?", 1))
	}

}
